<template>
  <a-upload
    v-bind="$attrs"
    v-model:file-list="fileList"
    :name="name"
    :accept="accept"
    :data="{ token }"
    list-type="picture-card"
    class="avatar-uploader"
    action="/back/sys/file/upload"
    :show-upload-list="showUploadListOptions"
    :with-credentials="true"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <div v-if="fileList.length < limit">
      <plus-outlined />
      <div class="ant-upload-text">
        {{ tip }}
      </div>
    </div>
  </a-upload>
</template>
<script lang="ts" setup>
import { PlusOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import type { UploadChangeParam, UploadFile } from "ant-design-vue";

export interface IUploadImgProps {
  accept?: string;
  limit?: number;
  maxSize?: number;
  name?: string;
  tip?: string;
  modelValue: string | string[];
}

const props = withDefaults(defineProps<IUploadImgProps>(), {
  accept: ".png,.jpg,.jpeg",
  limit: 1,
  name: "file",
  maxSize: 10240,
  tip: "上传图片",
});

const showUploadListOptions = {
  showPreviewIcon: false,
};
const fileList = ref<UploadFile[]>([]);

watch(
  () => props.modelValue,
  (val) => {
    if (fileList.value.length > 0 && val) {
      return;
    }
    if (!Array.isArray(val)) {
      val = val ? [val] : [];
    }
    fileList.value = val.map((url, index) => ({
      uid: index + "",
      name: index + "",
      url,
    }));
  }
);
const token = sessionStorage.getItem("token");
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status === "uploading") {
    return;
  }
  if (info.file.status === "removed") {
    updateValue();
    return;
  }
  const res = info.file.response || {};
  if (res.data) {
    info.file.url = res.data;
    updateValue();
  } else {
    message.error(res.msg || "上传失败,请稍后重试");
  }
};

const emit = defineEmits(["update:modelValue"]);

function updateValue() {
  const value = (fileList.value[0] || { url: "" }).url;
  emit("update:modelValue", value);
}

const sizeTip = $computed(() => {
  return props.maxSize >= 1024
    ? `${props.maxSize / 1024}M`
    : `${props.maxSize}KB`;
});
const beforeUpload = (file: UploadFile) => {
  // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  // if (!isJpgOrPng) {
  //   message.error('You can only upload JPG file!');
  // }
  const isLt2M = (file.size || 0) / 1024 < props.maxSize;
  if (!isLt2M) {
    message.error(`上传的图片需要小于${sizeTip}`);
  }
  return isLt2M;
};
</script>
<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
